<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\MaterielProductContentModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use App\V3\V3_2_7\Models\StorageManageModel;

class CommonStorageOperateService
{
    public static function exportData($parentId, $data)
    {
        $keyword = empty($data['keyword'])?'':$data['keyword'];
        $condition = [];
        if(!empty($data['materiel_class_id'])) {
            $condition['c.id'] = ['EQ' => $data['materiel_class_id']];
        }

        if(isset($data['is_product_materiel'])) {
            $condition['a.is_product_materiel'] = ['EQ' => $data['is_product_materiel']];
        }

        if(isset($data['is_product_storage'])) {
            $condition['e.is_product_storage'] = ['EQ' => $data['is_product_storage']];
        }

        //获取导出的数据
        $exportData = [];
        switch($data['order_type']) {
            case 0:
                $exportData = self::defaultOrder($parentId, $keyword, $condition, $data);
                break;
            case 1:
                $exportData = self::orderByInstorageNum($parentId, $keyword, $condition, $data);
                break;
            case 2:
                $exportData = self::orderByCharset($parentId, $keyword, $condition, $data);
                break;
        }

        return $exportData;
    }

    //默认排序方式-综合排序
    private static function defaultOrder($parentId, $keyword,$condition,$data)
    {
        $alertSort = StorageManageService::alertSort($parentId, $keyword, $condition, $data);

        $notAlertSort = StorageManageService::notAlertSort($parentId, $keyword, $condition, $data);

        if (!empty($alertSort) && !empty($notAlertSort)) {
            $arr = array_merge($alertSort, $notAlertSort);
        } else if (!empty($alertSort) && empty($notAlertSort)) {
            $arr = $alertSort;
        } else {
            $arr = $notAlertSort;
        }

        return $arr;
    }

    //库存数排序
    private static function orderByInstorageNum($parentId, $keyword, $condition, $data)
    {
        $result = StorageManageModel::list($parentId, $keyword, $condition, $data);

        $test1 = [];
        foreach($result as $vv1) {
            $test1[$vv1['type_id']][] = $vv1;

        }

        $arr1 = [];
        foreach($test1 as $vaa) {
            foreach($vaa as $vaaa) {
                $arr1[] = $vaaa;
            }
        }

        $keywordLength = strlen($keyword);
        $arr = [];

        foreach($arr1 as $key =>  $value) {
            if(substr($value['materiel_name'], 0, $keywordLength) == $keyword) {
                $arr[$key] = $value;
                unset($arr1[$key]);
            }
        }

        foreach($arr1 as $k => $val) {
            if(preg_match('/'.$data['keyword'].'/', $val['materiel_name'])) {
                $arr[$k] = $val;
                unset($arr1[$k]);
            }
        }

        foreach($arr1 as $k1 => $v1) {
            $arr[$k1] = $v1;
        }

        if($data['order_by'] == 'desc') {
            usort($arr, function($a, $b) {
                if($a['in_storage_num'] == $b['in_storage_num']) {
                    return 0;
                }
                return ($a['in_storage_num'] > $b['in_storage_num'])?-1:1;
            });
        }
        else {
            usort($arr, function($a, $b) {
                if($a['in_storage_num'] == $b['in_storage_num']) {
                    return 0;
                }
                return ($a['in_storage_num'] > $b['in_storage_num'])?1:-1;
            });
        }

        return $arr;
    }

    //首字母排序
    private static function orderByCharset($parentId, $keyword, $condition, $data)
    {
        $result = self::orderByCharsetData($parentId, $keyword, $condition, $data);

        foreach($result as &$value) {
            $materielTypeInfo = MaterielTypeModel::where('id', $value['type_id'])->first();
//                'b.materiel_name',
//                'b.type_name',
//                'b.materiel_no',
//                'b.materiel_img',
//                'b.is_product_materiel',
//                'b.remark','b.two_materiel_name'
//                'b.is_use_serial',
//                'b.materiel_unit',
            $value['bar_code'] = $materielTypeInfo['bar_code'];
            $value['two_materiel_name'] = $materielTypeInfo['two_materiel_name'];
            $value['materiel_name'] = $materielTypeInfo['materiel_name'];
            $value['type_name'] = $materielTypeInfo['type_name'];
            $value['materiel_no'] = $materielTypeInfo['materiel_no'];
            $value['materiel_img'] = $materielTypeInfo['materiel_img'];
            $value['is_product_materiel'] = $materielTypeInfo['is_product_materiel'];
            $value['remark'] = $materielTypeInfo['remark'];
            $value['is_use_serial'] = $materielTypeInfo['is_use_serial'];
            $value['materiel_unit'] = $materielTypeInfo['materiel_unit'];
            $value['lower_selling_price'] = $materielTypeInfo['lower_selling_price'];
            $value['selling_price'] = $materielTypeInfo['selling_price'];
            $value['is_product_materiel'] = $materielTypeInfo['is_product_materiel'];

            if(!empty($value['materiel_img'])) {
                $materielImg = array_filter(explode(',', $value['materiel_img']), function($v) { return $v !== ''; });

                $value['materiel_img'] = $materielImg[0];
            }

            if($materielTypeInfo['is_product_materiel'] == 1) {
                $productList = MaterielProductContentModel::select(
                    'a.id',
                    'b.materiel_name',
                    'b.type_name',
                    'b.materiel_img',
                    'b.materiel_no',
                    'a.product_id',
                    'a.num',
                    'a.price',
                    'a.type_id',
                    'a.total_price'
                )
                    ->from('materiel_product_content as a')
                    ->leftJoin('materiel_type as b','b.id','=','a.type_id')
                    ->where('a.product_id',$value['type_id'])->get()->toArray();

//                $value['forecasting_num'] = self::forecastingOfProductUsefulNum($value['type_id']);

                foreach($productList as &$val) {
                    if(!empty($val['materiel_img'])) {
                        $materielImg = array_filter(explode(',',$val['materiel_img']), function($v) { return $v !== '';});
                        $val['materiel_img'] = $materielImg[0];
                    }
                }

                $value['product_content'] = $productList;
            }
            else {
                $value['forecasting_num'] = 0;
                $value['product_content'] = [];
            }
        }

        return $result;
    }

    public static function orderByCharsetData($parentId, $keyword, $condition, $data)
    {
        $query = StorageManageModel::query()
            ->select(
                'storage_manage.id',
                'storage_manage.type_id',
                'storage_manage.materiel_mean_cost',
                'storage_manage.storage_id',
                'e.storage_name',
                'e.storage_address',
                'storage_manage.in_storage_num',
                'storage_manage.alert_num',
                'storage_manage.virtual_storage_num',
                'd.id as f_class_id',
                'd.class_name as f_class_name',
                'd.class_no as f_class_no',
                'c.id as s_class_id',
                'c.class_name as s_class_name',
                'c.class_no as s_class_no',
                'storage_manage.shelf_id',
                'storage_manage.location_id',
                's.shelf_name',
                'l.location_name',
                'storage_manage.sort_flag'
            )
            ->leftJoin('materiel_class as c', 'storage_manage.materiel_class_id', '=', 'c.id')
            ->leftJoin('materiel_class as d', 'd.id', '=', 'c.parent_id')
            ->leftJoin('storage as e', 'e.id', '=', 'storage_id')
            ->leftJoin('storage_shelf as s','storage_manage.shelf_id','=','s.id')
            ->leftJoin('storage_shelf_location as l','storage_manage.location_id','=','l.id')
            ->where($parentId)
            ->where('storage_manage.delete_flag', 0)
            ->where($condition);

        if(isset($data['storage_id']) && $data['storage_id'] != 0) {
            $query->where('storage_manage.storage_id', $data['storage_id']);
        }

        return $query->where(function($query) use ($keyword) {
            $query->whereHas('serialInfo', function($query) use ($keyword) {
                $query->where('serial_no', 'like', '%'.$keyword.'%')
                    ->where('package_id', 0);
            })
                ->orWhere('storage_manage.materiel_name', 'like', '%'.$keyword.'%')
                ->orWhere('storage_manage.type_name', 'like','%'.$keyword.'%')
                ->orWhere('storage_manage.materiel_no', 'like', '%'.$keyword.'%')
                ->orWhere('c.class_name', 'like', '%'.$keyword.'%')
                ->orWhere('c.class_no', 'like', '%'.$keyword.'%')
                ->orWhere('d.class_name', 'like', '%'.$keyword.'%')
                ->orWhere('d.class_no', 'like', '%'.$keyword.'%');
        })
            ->orderByRaw("CONVERT(materiel_name USING gbk) COLLATE gbk_chinese_ci ".$data['order_by'])
            ->get()->toArray();
    }
}
